package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gspeed/app/dist"
	"gspeed/app/http/validator/request"
	"gspeed/app/utils/response"
	"gspeed/bootstrap/global"
)

type authController struct{}

var AuthController authController

// 注册
func (a *authController) Register(c *gin.Context) {
	return
}

// 登录
func (a *authController) Login(c *gin.Context) (interface{}, error) {

	return nil, nil
}

// 退出
func (a *authController) Logout(c *gin.Context) {

}

// 添加权限策略
func (a *authController) AddPolicy(c *gin.Context) {
	addPolicy := request.AddPolicy{}
	if err := c.ShouldBind(&addPolicy); err != nil {
		response.Err(c, response.WithData(err), response.WithCode(dist.ValidParamErr))
		return
	}
	result, err := global.Auth.AddPolicy(addPolicy.Subject, addPolicy.Object, addPolicy.Action)
	if err != nil {
		fmt.Println(err.Error())
	}

	if result {
		// 重新加载策略
		a.reloadPolicy()
		response.Ok(c)
		return
	} else {
		response.Err(c)
		return
	}
}

// 移除权限策略
func (a *authController) RemovePolicy(c *gin.Context) {
	addPolicy := request.AddPolicy{}
	if err := c.ShouldBind(&addPolicy); err != nil {
		response.Err(c, response.WithData(err), response.WithCode(dist.ValidParamErr))
		return
	}

	result, err := global.Auth.RemovePolicy(addPolicy.Subject, addPolicy.Object, addPolicy.Action)
	if err != nil {
		fmt.Println(err.Error())
	}

	if result {
		// 重新加载策略
		a.reloadPolicy()
		response.Ok(c)
		return
	} else {
		response.Err(c)
		return
	}
}

// 添加分组
func (a *authController) AddGroup(c *gin.Context) {
	addGroup := request.AddGroup{}
	if err := c.ShouldBind(&addGroup); err != nil {
		response.Err(c, response.WithData(err), response.WithCode(dist.ValidParamErr))
		return
	}
	result, err := global.Auth.AddGroupingPolicy(addGroup.Subject, addGroup.Policy)
	if err != nil {
		fmt.Println(err.Error())
	}

	if result {
		// 重新加载策略
		a.reloadPolicy()
		response.Ok(c)
		return
	} else {
		response.Err(c)
		return
	}
}

// 从分组中移除策略
func (a *authController) RemoveFromGroup(c *gin.Context) {
	addGroup := request.AddGroup{}
	if err := c.ShouldBind(&addGroup); err != nil {
		response.Err(c, response.WithData(err), response.WithCode(dist.ValidParamErr))
		return
	}
	result, err := global.Auth.RemoveGroupingPolicy(addGroup.Subject, addGroup.Policy)
	if err != nil {
		fmt.Println(err.Error())
	}

	if result {
		// 重新加载策略
		a.reloadPolicy()
		response.Ok(c)
		return
	} else {
		response.Err(c)
		return
	}
}

// 从新加载配置
func (a *authController) reloadPolicy() {
	err := global.Auth.LoadPolicy()
	if err != nil {
		panic(err)
	}
}
